package com.kaylyn.item;

import java.awt.Color;
import java.awt.Component;
import java.io.IOException;
import java.net.URLDecoder;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

import player.PlayerAdapter;
import player.PlayerControl;
import player.PlayerFactory;

import com.kaylyn.util.Initializable;
import com.kaylyn.util.LevelListener;
import com.kaylyn.util.MusicPlayer;
import com.kaylyn.util.Resource;

public class Video extends JLabel implements Initializable, LevelListener {

	private static final long serialVersionUID = 1L;
	private PlayerControl player;
	private Component component;
	private JLabel label;

	public Video() {
		setSize(840, 560);
		setIcon(new ImageIcon(Resource.loadImage("1c0353eq39f1.303ca7.jpg")));
		setOpaque(true);
		label = new JLabel();
		final int thickness = 2;
		label.setBorder(BorderFactory.createLineBorder(Color.black, thickness));
		label.setSize(320 + 2 * thickness, 240 + 2 * thickness);
		label.setLocation(getWidth() / 2 - label.getWidth() / 2, getHeight()
				/ 2 - label.getHeight() / 2);
		label.setOpaque(true);
		label.setIcon(new ImageIcon(Resource.loadBufferedImage(
				"uvs090911-001.BMP", label.getSize())));
		add(label);
		try {
			player = PlayerFactory.createLightweightMPEG4Player();
			component = player.getRendererComponent();
			component.setLocation(thickness, thickness);
			player.open(URLDecoder.decode(Video.class.getResource("Video.mp4").getPath(),  "UTF-8"));
			player.start();
			label.add(component);
			player.addListener(new PlayerAdapter() {

				@Override
				public void preferSize(int w, int h) {
					component.setSize(w, h);
				}

				@Override
				public void playerTime(long arg0) {
					if (arg0 > player.getDuration()) {
						try {
							player.stop();
							player.start();
						} catch (IllegalStateException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void start() {
		MusicPlayer.setLevelListener(this);
		MusicPlayer.setEnable(false);
	}

	@Override
	public void stop() {
		try {
			MusicPlayer.setLevelListener(null);
			MusicPlayer.setEnable(true);
			label.remove(component);
			player.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setLevel(float level) {
		player.setVolume(level);
	}

}
